﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Citi.RoutineBase;
using System.IO;
using Citi.ProcureToPay.Domain;
using Citi.Import.Util;
using Citi.Helpers;
using System.Configuration;
using System.Data;
using System.Globalization;

namespace Citi.ProcureToPay.SchedulerUi
{
    public class EntriesImport : IExecutableRoutine
    {
        public IEnumerable<RoutineParameter> Parameters
        {
            get
            {
                return new List<RoutineParameter> { 
                    new RoutineParameter{ Description = "Excel Path", Name = "ExcelPath", Nullable= false, Required = true, Type = typeof(string)},
                };
            }
        }

        public void Rollback(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }

        public void Start(DateTime scheduledDate, ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            var excelPath = parameters["ExcelPath"].ToString();
            currentAction.Description = string.Format("Looking for Entries Files in {0}", excelPath);
            var fileName = Directory.GetFiles(excelPath).OrderByDescending(x => File.GetLastWriteTime(x)).First();

            if (fileName != null && fileName.Any())
            {
                new Entry().DeleteData(DateTime.Today);
                currentAction.Description = string.Format("The file {0} was found", Path.GetFileName(fileName));
                UpdatingDatabase(fileName, currentAction);
            }
        }

        private static void UpdatingDatabase(string filePath, ICurrentAction currentAction)
        {
            currentAction.Description = "Reading File";

            var errors = new List<Error>();
            var dataTable = Conversion.ReadExcel(filePath, ref errors, null, 4);

            dataTable.Columns.Add("DateConverted", typeof(DateTime));
            dataTable.Columns.Add("InvoiceDateConverted", typeof(DateTime));
            var dateFormat = "d-MMM-yy";
            var cultureInfo = new CultureInfo("pt-BR");

            currentAction.Description = "Converting dates";

            foreach (DataRow row in dataTable.Rows)
            {
                DateTime dateConverted;

                if (DateTime.TryParseExact(row["Date"] != null ? row["Date"].ToString() : string.Empty, dateFormat, cultureInfo, DateTimeStyles.None, out dateConverted))
                    row["DateConverted"] = dateConverted;

                if (DateTime.TryParseExact(row["Invoice Date"] != null ? row["Invoice Date"].ToString() : string.Empty, dateFormat, cultureInfo, DateTimeStyles.None, out dateConverted))
                    row["InvoiceDateConverted"] = dateConverted;
            }

            var lastRow = dataTable.Rows[dataTable.Rows.Count - 1];

            if (lastRow[0] != null && lastRow[0].ToString().ToUpper().StartsWith("SUM"))
                lastRow.Delete();

            currentAction.Description = "Saving";
            SqlHelper.CopyTo("Entry", ConfigurationManager.ConnectionStrings["ProcureToPay"].ConnectionString, Entry.ExcelColumnMappings, dataTable, 30000);
            currentAction.Description = "Saved successfully";
        }

        public void Stop(ref ICurrentAction currentAction, Dictionary<string, object> parameters)
        {

        }
    }
}
